#include "securitytcpcommunication.h"

securityTcpCommunication::securityTcpCommunication()
    : CommunicationInterface()
    , currentReceiveBufferIndex(0)
{
    //这里需要连接信号，因此需要将其作为元对象系统的
    QObject::connect(&tcpSocket,
                     &QTcpSocket::readyRead,
                     this,
                     &securityTcpCommunication::onReadyRead);
    QObject::connect(&tcpSocket,
                     &QTcpSocket::connected,
                     this,
                     &securityTcpCommunication::onConnected);
    QObject::connect(&tcpSocket,
                     &QTcpSocket::errorOccurred,
                     this,
                     &securityTcpCommunication::onError);
    QObject::connect(&tcpSocket,
                     &QTcpSocket::disconnected,
                     this,
                     &securityTcpCommunication::onError);
}

void securityTcpCommunication::connect(const QString &hostAddress, const quint64 &hostPort)
{
    tcpSocket.connectToHost(hostAddress, hostPort);
}

void securityTcpCommunication::sendData(const QByteArray &data)
{
    tcpSocket.write(data);
}

QByteArray securityTcpCommunication::readData()
{
    QByteArray tmp = transBuffer;
    transBuffer.clear();

    return tmp;
}

void securityTcpCommunication::onReadyRead()
{
    while (tcpSocket.bytesAvailable()) {
        //获取当前索引的缓冲区
        QByteArray *currentReceiveBuffer = &receiveBuffers[currentReceiveBufferIndex];

        if (!currentReceiveBuffer->isEmpty()) {
            //切换缓冲区
            currentReceiveBufferIndex = (currentReceiveBufferIndex + 1) % 2; // 切换到下一个缓冲区
            currentReceiveBuffer = &receiveBuffers[currentReceiveBufferIndex];
        }

        qint64 readBytes = tcpSocket.read(currentReceiveBuffer->data(), expectedPacketSize);
        if (readBytes > 0) {
            transBuffer.push_back(*currentReceiveBuffer);
            emit onDataReadCompleted();
            currentReceiveBuffer->clear();
        }
    }
}

void securityTcpCommunication::onConnected()
{
    qDebug() << "Successfully connected to the TcpServer!";
}

void securityTcpCommunication::onError(QAbstractSocket::SocketError socketError)
{
    qDebug() << "Connection failed with error:" << socketError;
}

void securityTcpCommunication::onDisconnected()
{
    qDebug() << "The TCP server has been disconnected successfully!";
}
